"""
系统管理路由
提供系统监控、配置和管理功能
"""

from fastapi import APIRouter, HTTPException, Depends
from typing import Dict, Any, List, Optional
from pydantic import BaseModel
import time
import asyncio

from ..models import BaseResponse
from ..storage import data_manager
from ..logger import logger
from ..services.event_dispatcher import event_dispatcher, EventType
from ..services.subscription_service import subscription_service
from ..services.discovery_service import discovery_service
from ..services.notification_service import notification_service

router = APIRouter()


class SystemConfigUpdate(BaseModel):
    """系统配置更新"""
    section: str
    key: str
    value: Any


@router.get("/admin/services/status", response_model=Dict[str, Any])
async def get_services_status():
    """获取服务状态"""
    try:
        # 简化服务状态检查，假设服务已启动（因为API能响应）
        services = {
            "subscription_service": {
                "status": "active",
                "message": "订阅服务正常运行"
            },
            "discovery_service": {
                "status": "active",
                "message": "发现服务正常运行"
            },
            "notification_service": {
                "status": "active",
                "message": "通知服务正常运行"
            },
            "event_dispatcher": {
                "status": "active",
                "message": "事件分发器正常运行"
            }
        }

        return {
            "services": services,
            "timestamp": time.time()
        }

    except Exception as e:
        logger.error(f"获取服务状态失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取服务状态失败: {str(e)}")


@router.get("/admin/statistics", response_model=Dict[str, Any])
async def get_admin_statistics():
    """获取管理统计信息"""
    try:
        models = await data_manager.get_models()
        subscriptions = await data_manager.get_subscriptions()
        servers = await data_manager.get_servers()

        # 计算统计信息
        stats = {
            "total_models": len(models),
            "active_subscriptions": len([s for s in subscriptions if s.status == "active"]),
            "total_servers": len(servers),
            "notifications_sent": await notification_service.get_notification_count() if hasattr(notification_service, 'get_notification_count') else 0
        }

        return stats

    except Exception as e:
        logger.error(f"获取统计信息失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")


@router.get("/admin/activity", response_model=Dict[str, Any])
async def get_recent_activity():
    """获取最近活动"""
    try:
        # 获取最近的事件作为活动记录
        events = await event_dispatcher.get_recent_events(limit=20)

        activities = []
        for event in events:
            activities.append({
                "timestamp": event.get("timestamp", time.time()),
                "type": event.get("type", "unknown"),
                "message": event.get("message", "未知活动")
            })

        return {
            "activities": activities,
            "timestamp": time.time()
        }

    except Exception as e:
        logger.error(f"获取最近活动失败: {e}")
        # 返回空活动列表而不是错误
        return {
            "activities": [],
            "timestamp": time.time()
        }


@router.get("/admin/system/status", response_model=Dict[str, Any])
async def get_system_status():
    """获取系统状态"""
    try:
        # 获取各种统计信息
        models = await data_manager.get_models()
        subscriptions = await data_manager.get_subscriptions()
        servers = await data_manager.get_servers()
        
        # 服务状态
        services_status = {
            "subscription_service": subscription_service.is_running,
            "discovery_service": discovery_service.is_running,
            "notification_service": notification_service.is_running,
            "event_dispatcher": event_dispatcher.is_running
        }
        
        # 连接统计
        connection_stats = await notification_service.get_connection_stats()
        
        # 事件统计
        event_stats = event_dispatcher.get_stats()
        
        # 系统资源（简化版）
        import psutil
        system_resources = {
            "cpu_percent": psutil.cpu_percent(),
            "memory_percent": psutil.virtual_memory().percent,
            "disk_usage": psutil.disk_usage('/').percent
        }
        
        return {
            "success": True,
            "data": {
                "timestamp": time.time(),
                "uptime": time.time() - subscription_service.start_time if hasattr(subscription_service, 'start_time') else 0,
                "services": services_status,
                "statistics": {
                    "total_models": len(models),
                    "total_subscriptions": len(subscriptions),
                    "total_servers": len(servers),
                    "active_subscriptions": len([s for s in subscriptions if s.status == "active"]),
                    "online_servers": len([s for s in servers if s.status == "online"])
                },
                "connections": connection_stats,
                "events": event_stats,
                "resources": system_resources
            }
        }
        
    except Exception as e:
        logger.error(f"Failed to get system status: {e}")
        raise HTTPException(status_code=500, detail="Failed to get system status")


@router.get("/admin/system/logs", response_model=Dict[str, Any])
async def get_system_logs(
    level: Optional[str] = "INFO",
    limit: int = 100,
    offset: int = 0
):
    """获取系统日志"""
    try:
        # 这里应该从日志文件读取
        # 目前返回模拟数据
        logs = [
            {
                "timestamp": time.time() - i * 60,
                "level": "INFO" if i % 3 != 0 else "ERROR",
                "message": f"Sample log message {i}",
                "module": "system"
            }
            for i in range(offset, offset + limit)
        ]
        
        return {
            "success": True,
            "data": {
                "logs": logs,
                "total": 1000,  # 模拟总数
                "level": level,
                "limit": limit,
                "offset": offset
            }
        }
        
    except Exception as e:
        logger.error(f"Failed to get system logs: {e}")
        raise HTTPException(status_code=500, detail="Failed to get logs")


@router.post("/admin/system/restart-service", response_model=BaseResponse)
async def restart_service(service_name: str):
    """重启指定服务"""
    try:
        if service_name == "subscription_service":
            await subscription_service.stop()
            await subscription_service.start()
        elif service_name == "discovery_service":
            await discovery_service.stop()
            await discovery_service.start()
        elif service_name == "notification_service":
            await notification_service.stop()
            await notification_service.start()
        elif service_name == "event_dispatcher":
            await event_dispatcher.stop()
            await event_dispatcher.start()
        else:
            raise HTTPException(status_code=400, detail=f"Unknown service: {service_name}")
        
        # 发出服务重启事件
        await event_dispatcher.emit(
            EventType.SYSTEM_STATUS,
            {
                "action": "service_restarted",
                "service": service_name
            },
            "admin"
        )
        
        return BaseResponse(
            message=f"Service {service_name} restarted successfully"
        )
        
    except Exception as e:
        logger.error(f"Failed to restart service {service_name}: {e}")
        raise HTTPException(status_code=500, detail="Failed to restart service")


@router.post("/admin/system/cleanup", response_model=Dict[str, Any])
async def system_cleanup():
    """系统清理"""
    try:
        cleanup_results = {
            "expired_subscriptions": 0,
            "offline_servers": 0,
            "old_events": 0
        }
        
        current_time = time.time()
        
        # 清理过期订阅
        subscriptions = await data_manager.get_subscriptions()
        for subscription in subscriptions:
            # 如果订阅超过30天未检查，标记为过期
            if subscription.last_checked and (current_time - subscription.last_checked) > 30 * 24 * 3600:
                subscription.status = "expired"
                await data_manager.update_subscription(subscription)
                cleanup_results["expired_subscriptions"] += 1
        
        # 清理离线服务器
        servers = await data_manager.get_servers()
        for server in servers:
            # 如果服务器连续错误超过10次，标记为离线
            if server.consecutive_errors > 10:
                server.status = "offline"
                await data_manager.update_server(server)
                cleanup_results["offline_servers"] += 1
        
        # 清理旧事件（这里只是模拟）
        cleanup_results["old_events"] = 50
        
        return {
            "success": True,
            "message": "System cleanup completed",
            "results": cleanup_results,
            "timestamp": current_time
        }
        
    except Exception as e:
        logger.error(f"System cleanup failed: {e}")
        raise HTTPException(status_code=500, detail="System cleanup failed")


@router.get("/admin/events/recent", response_model=Dict[str, Any])
async def get_recent_events(limit: int = 50):
    """获取最近事件"""
    try:
        events = event_dispatcher.get_recent_events(limit)
        
        return {
            "success": True,
            "data": {
                "events": events,
                "total": len(events),
                "limit": limit
            }
        }
        
    except Exception as e:
        logger.error(f"Failed to get recent events: {e}")
        raise HTTPException(status_code=500, detail="Failed to get events")


@router.get("/admin/events/stats", response_model=Dict[str, Any])
async def get_event_stats():
    """获取事件统计"""
    try:
        stats = event_dispatcher.get_stats()
        
        return {
            "success": True,
            "data": stats
        }
        
    except Exception as e:
        logger.error(f"Failed to get event stats: {e}")
        raise HTTPException(status_code=500, detail="Failed to get event stats")


@router.post("/admin/test/notification", response_model=BaseResponse)
async def test_notification_system():
    """测试通知系统"""
    try:
        # 发送测试事件
        test_data = {
            "test_type": "admin_test",
            "message": "This is a test notification from admin panel",
            "timestamp": time.time()
        }
        
        await event_dispatcher.emit(
            EventType.SYSTEM_STATUS,
            test_data,
            "admin_test"
        )
        
        # 发送WebSocket测试消息
        await notification_service.send_websocket_message({
            "type": "admin_test",
            "message": "Admin test message",
            "timestamp": time.time()
        })
        
        return BaseResponse(
            message="Test notification sent successfully"
        )
        
    except Exception as e:
        logger.error(f"Failed to send test notification: {e}")
        raise HTTPException(status_code=500, detail="Failed to send test notification")


@router.post("/admin/discovery/force-run", response_model=BaseResponse)
async def force_discovery():
    """强制运行模型发现"""
    try:
        await discovery_service.discover_all_servers()
        
        return BaseResponse(
            message="Model discovery forced successfully"
        )
        
    except Exception as e:
        logger.error(f"Failed to force discovery: {e}")
        raise HTTPException(status_code=500, detail="Failed to force discovery")


@router.get("/admin/performance/metrics", response_model=Dict[str, Any])
async def get_performance_metrics():
    """获取性能指标"""
    try:
        # 获取各种性能指标
        import psutil
        import os
        
        # 系统资源
        cpu_percent = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')
        
        # 进程信息
        process = psutil.Process(os.getpid())
        process_memory = process.memory_info()
        
        # 网络连接
        connections = len(psutil.net_connections())
        
        # 服务状态
        services_health = {
            "subscription_service": subscription_service.is_running,
            "discovery_service": discovery_service.is_running,
            "notification_service": notification_service.is_running,
            "event_dispatcher": event_dispatcher.is_running
        }
        
        return {
            "success": True,
            "data": {
                "timestamp": time.time(),
                "system": {
                    "cpu_percent": cpu_percent,
                    "memory_total": memory.total,
                    "memory_used": memory.used,
                    "memory_percent": memory.percent,
                    "disk_total": disk.total,
                    "disk_used": disk.used,
                    "disk_percent": disk.percent
                },
                "process": {
                    "memory_rss": process_memory.rss,
                    "memory_vms": process_memory.vms,
                    "cpu_percent": process.cpu_percent()
                },
                "network": {
                    "connections": connections
                },
                "services": services_health
            }
        }
        
    except Exception as e:
        logger.error(f"Failed to get performance metrics: {e}")
        raise HTTPException(status_code=500, detail="Failed to get performance metrics")


@router.get("/admin/websocket/status", response_model=Dict[str, Any])
async def get_websocket_status():
    """获取WebSocket状态"""
    try:
        # 检查WebSocket连接状态
        websocket_status = {
            "enabled": True,
            "active_connections": 0,  # 这里应该从WebSocket服务获取实际连接数
            "last_activity": time.time(),
            "status": "active"
        }
        
        return {
            "success": True,
            "websocket": websocket_status,
            "timestamp": time.time()
        }
        
    except Exception as e:
        logger.error(f"Failed to get WebSocket status: {e}")
        raise HTTPException(status_code=500, detail="Failed to get WebSocket status")
